﻿using System;
using System.Text;
using System.Web.Mvc;
using WSPay.Application;
using WSPay.Common;
using WSPay.Common.Log;
using WSPay.Core.DTO;
using WSPay.Domain;
using WSPay.Weixin;

namespace WSPay.Web.Controllers {
    public class WeiXinController : Controller {
        private readonly NLogLogger nlog;

        private readonly IPaymentService PaymentService;

        public WeiXinController(IWSBService wsbService, IPaymentService paymentService) {
            WSBService = wsbService;
            PaymentService = paymentService;
            nlog = new NLogLogger();
        }

        public IWSBService WSBService { get; }

        /// <summary>
        /// 创建支付订单
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CreateChargeOrder(ChargeDto dto) {
            try {
                var order = WSBService.CreateWSBRechargeBillForWeix(dto);
                return Json(new {Code = "0000", OrderId = order.ID});
            }
            catch (Exception ex) {
                return Json(new {Code = "0001", Message = ex.Message});
            }

           
            
        }
        /// <summary>
        ///     用户充值(pc扫码支付)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ChargeQr(int orderId) {
            try {
                //var order = WSBService.CreateWSBRechargeBillForWeix(dto);
                var order = WSBService.GetRechargeOrder(orderId);
                var noticeUrl = Url.AbsoluteAction("Notify", "WeiXin");
                var amount = order.PayAmount;
                if (amount < 1)
                    throw new ApplicationException("充值金额需大于1");
                var data = new WxPayData();
                data.SetValue("body", "文史天地用户充值"); //商品描述
                data.SetValue("attach", "文史天地用户充值"); //附加数据
                data.SetValue("out_trade_no", order.OrderId); //随机字符串
                data.SetValue("total_fee", (order.PayAmount * 100).ToString("0")); //总金额
                //data.SetValue("total_fee", (1).ToString("0")); //总金额
                data.SetValue("time_start", order.CreateTime.ToString("yyyyMMddHHmmss")); //交易起始时间
                data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间
                data.SetValue("goods_tag", "文史天地"); //商品标记
                data.SetValue("trade_type", "NATIVE"); //交易类型
                data.SetValue("product_id", order.OrderId); //商品ID
                data.SetValue("spbill_create_ip",
                    Request.ServerVariables.Get("Local_Addr")); //终端IP APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
                data.SetValue("notify_url", noticeUrl);
                var result = WxPayApi.UnifiedOrder(data); //调用统一下单接口
                var url = result.GetValue("code_url").ToString(); //获得统一下单接口返回的二维码链接
                var qrcode = new MakeQRCode().GetQRCode(url);
                return File(qrcode, "image/jpeg");
                //return Json(new {WSBPayMessageDTO.Code0000, Code_Url = url});
            }
            catch (Exception e) {
                throw new ApplicationException(e.Message);
            }
        }

        /// <summary>
        ///     微信扫码付
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PayWithWeiXin(string orderId) {
            try {
                var noticeUrl = Url.AbsoluteAction("PayNotify", "WeiXin");
                //var ruturnUrl = Url.AbsoluteAction("RuturnUrl", "Payment");
                var payOrder = PaymentService.GetPaymentOrderBuyOrder(orderId);
                var data = new WxPayData();
                data.SetValue("body", "文史天地微信支付"); //商品描述
                data.SetValue("attach", "文史天地微信支付"); //附加数据
                data.SetValue("out_trade_no", payOrder.OrderId); //随机字符串
                //data.SetValue("total_fee", (payOrder.PayAmount * 100).ToString("0")); //总金额
                data.SetValue("total_fee", (1).ToString("0")); //总金额
                data.SetValue("time_start", payOrder.CreateTime.ToString("yyyyMMddHHmmss")); //交易起始时间
                data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss")); //交易结束时间
                data.SetValue("goods_tag", "文史天地"); //商品标记
                data.SetValue("trade_type", "NATIVE"); //交易类型
                data.SetValue("product_id", payOrder.OrderId); //商品ID
                data.SetValue("spbill_create_ip",
                    Request.ServerVariables.Get("Local_Addr")); //终端IP APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
                data.SetValue("notify_url", noticeUrl);
                var result = WxPayApi.UnifiedOrder(data); //调用统一下单接口
                if (result.GetValue("return_code").ToString().ToUpper() != "SUCCESS") {
                    return Json(new {Code = "0001",Message=result.GetValue("return_msg") });
                }
                //var qr = "http://www.baidu.com";
                 string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
                //var url = qr; //获得统一下单接口返回的二维码链接
                var qrcode = new MakeQRCode().GetQRCode(url);
                return File(qrcode, "image/jpeg");
            }
            catch (Exception e) {
                throw new ApplicationException(e.Message);
            }
        }

        /// <summary>
        ///     支付回调通知
        /// </summary>
        /// <returns></returns>
        public ActionResult Notify() {
            var s = Request.InputStream;
            var count = 0;
            var buffer = new byte[1024];
            var builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            s.Flush();
            s.Close();
            s.Dispose();

            nlog.Info("Receive data from WeChat : " + builder);

            //转换数据格式并验证签名
            var data = new WxPayData();
           // var res = new WxPayData();
            try {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex) {
                //若签名错误，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                nlog.Error("Sign check error : " + res.ToXml());
                return Content(res.ToXml(), "text/xml");
            }

            nlog.Info("Check sign success");
            var transaction_id = data.GetValue("transaction_id").ToString();

            //查询订单，判断订单真实性
            if (!QueryOrder(transaction_id)) {
                //若订单查询失败，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                nlog.Error("Order query failure : " + res.ToXml());
                return Content(res.ToXml(), "text/xml");
            }
            var out_trade_no = data.GetValue("out_trade_no").ToString();

            var order = WSBService.GetRechargeOrder(out_trade_no);
            if (order.RechargeState == RechargeState.Completed || order.RechargeState == RechargeState.Completed) {
                WxPayData d = new WxPayData();
                d.SetValue("return_code", "SUCCESS");
                d.SetValue("return_msg", "OK");
                return Content(d.ToXml(), "text/xml");
            }

            //交易状态
            var trade_status = data.GetValue("return_code").ToString();
            if (trade_status == "SUCCESS") {
                WSBService.RechargeToWSBAccount(out_trade_no, transaction_id);
            }
            else {
                WSBService.RechargeFailure(out_trade_no);
                //return Json("fail");
            }
            WxPayData resdata = new WxPayData();
            resdata.SetValue("return_code", "SUCCESS");
            resdata.SetValue("return_msg", "OK");
            return Content(resdata.ToXml(), "text/xml");
            //return Json("success", JsonRequestBehavior.AllowGet);  //请不要修改或删除
        }
        public ActionResult PayNotify()
        {
            var s = Request.InputStream;
            var count = 0;
            var buffer = new byte[1024];
            var builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            s.Flush();
            s.Close();
            s.Dispose();

            nlog.Info("Receive data from WeChat : " + builder);

            //转换数据格式并验证签名
            var data = new WxPayData();
            // var res = new WxPayData();
            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                nlog.Error("Sign check error : " + res.ToXml());
                return Content(res.ToXml(), "text/xml");
            }

            nlog.Info("Check sign success");
            var transaction_id = data.GetValue("transaction_id").ToString();

            //查询订单，判断订单真实性
            if (!QueryOrder(transaction_id))
            {
                //若订单查询失败，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "订单查询失败");
                nlog.Error("Order query failure : " + res.ToXml());
                return Content(res.ToXml(), "text/xml");
            }

//            string out_trade_no = Request.Form["out_trade_no"];
//            //支付宝交易号
//            string trade_no = Request.Form["trade_no"];
//            //交易状态
//            string trade_status = Request.Form["trade_status"];
//            var order = PaymentService.GetPaymentOrder(out_trade_no);
//            if (Request.Form["trade_status"] == "TRADE_FINISHED")
//            {
//                PaymentService.FailurePay(order.ID, trade_no);
//                return Json("fail");
//            }
//            else if (Request.Form["trade_status"] == "TRADE_SUCCESS")//支付成功
//            {
//                PaymentService.SuccessPay(order.ID, trade_no, Request.Form["buyer_email"], Request.Form["buyer_id"]);
//            }


            var out_trade_no = data.GetValue("out_trade_no").ToString();
           // string trade_no = Request.Form["trade_no"];
            //交易状态
            var trade_status = data.GetValue("return_code").ToString();
            var appId = data.GetValue("appid").ToString();
            var mch_id = data.GetValue("mch_id").ToString();

            var order = PaymentService.GetPaymentOrder(out_trade_no);
            if (trade_status == "SUCCESS")
            {
                PaymentService.SuccessPay(order.ID, transaction_id, appId, mch_id);
                  
            }
            else
            {

                PaymentService.FailurePay(order.ID, transaction_id);
                //return Json("fail");
            }
            WxPayData resdata = new WxPayData();
            resdata.SetValue("return_code", "SUCCESS");
            resdata.SetValue("return_msg", "OK");
            return Content(resdata.ToXml(), "text/xml");
            //return Json("success", JsonRequestBehavior.AllowGet);  //请不要修改或删除
        }
        /// <summary>
        /// 查询扫码充值支付状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult QueryChareStatus(int id) {
            var order = WSBService.GetRechargeOrder(id);
            if (order.RechargeState != RechargeState.Unpaid) {
                return Json(new {Code = "0"}, JsonRequestBehavior.AllowGet);
            }
            return Json(new {Code = "1"},JsonRequestBehavior.AllowGet);
        }
        //查询订单
        private bool QueryOrder(string transaction_id) {
            var req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            var res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
                return true;
            return false;
        }
        //}
        //    return 
        //{

        //public ActionResult QueryPayOrder(string orderId)
    }
}